package com.ruoyi.tools.wechat;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.tools.pay.domain.WxPayBean;
import com.ruoyi.tools.util.http.BackEndHttpRequest;
import com.ruoyi.tools.util.param.ParamsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class TokenUtil {

    @Autowired
    WxPayBean wxPayBean;

    public String GetAccess_Token(){
        Object object = LocalCacheClient.get("access_token");
        if (object != null) {
            System.out.println("从缓存中获取token");
            return object.toString();
        }
        System.out.println("重新获取token");
        String url1="https://api.weixin.qq.com/cgi-bin/token";
        Map<String,Object> m =new LinkedHashMap<>();
        m.put("grant_type","client_credential");

        m.put("appid", wxPayBean.getAppId());
        m.put("secret",wxPayBean.getAppSecret());
        String access_token="";
        try {
            String str= BackEndHttpRequest.sendPost(url1, ParamsUtil.ParamBack(m));
            Map maps = (Map) JSONObject.parseObject(str);
            //System.out.println(maps);
             access_token = maps.get("access_token").toString();
            Integer expires_in = (Integer) maps.get("expires_in");
            LocalCacheClient.set("access_token", access_token, expires_in * 1000);
        }catch (Exception e){
            e.printStackTrace();
        }

        return access_token;
    }



}
